package com.huaxin.hxcloud.work;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.huaxin.common.BaseActivity;
import com.huaxin.common.BaseApp;
import com.huaxin.common.Entity.BaseDTO;
import com.huaxin.common.Entity.SignInfoDTO;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.common.tools.RequestHelper;
import com.huaxin.common.utils.DialogUtil;
import com.huaxin.common.utils.HxFileUtil;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.hxcloud.R;
import com.huaxin.hxcloud.find.view.adapter.ImagePickerAdapter;
import com.huaxin.hxcloud.fragment.SignFragment;
import com.huaxin.hxcloud.work.event.HxIsRefreshEventBus;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.baidu.mapapi.BMapManager.getContext;

/**
 * @author songxf
 *         created at 2017/7/27 13:53
 * @desc 签到-->编辑
 */

public class HxSignEditActivity extends BaseActivity implements ImagePickerAdapter.OnRecyclerViewItemClickListener, ImagePickerAdapter.OnDeleteItemClickListener {


    @BindView(R.id.more)
    TextView     mMore;
    @BindView(R.id.toolbar)
    Toolbar      mToolbar;
    @BindView(R.id.type_recyclerview)
    RecyclerView mTypeRecyclerview;
    @BindView(R.id.des_et)
    EditText     mDesEt;
    @BindView(R.id.picker_recyclerview)
    RecyclerView mPickerRecyclerview;
    @BindView(R.id.content_layout)
    LinearLayout mContentLayout;
    @BindView(R.id.covere_ly)
    FrameLayout  mCovereLy;
    private List<SignInfoDTO.SignTypesBean> mSignTypes;
    private int                             mSignId;
    private int                             mType;
    private HxMatterRecycleAdapter          mAdapter;
    private List<String> mMatters = new ArrayList<>();
    private SignInfoDTO mSignInfo;

    private static final String TAG         = "HxSignEditActivity";
    //选中数量限制
    private              int    maxImgCount = 3;
    private ArrayList<ImageItem> mSelImageList;
    public static final int IMAGE_ITEM_ADD       = -1;
    public static final int REQUEST_CODE_SELECT  = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
    private        ImagePickerAdapter mImagePickerAdapter;
    private static String             mImgCache; //缓存图片的路径

    @Override
    protected int getContentViewId() {
        return R.layout.activity_sign_edit;
    }

    @Override
    public void initView() {
        mToolbar.setTitle("描述");
        mMore.setText("编辑");

        mImgCache = getExternalCacheDir().getPath() + "/images/";

        ImagePicker picker = BaseApp.getImagePicker();
        if (picker != null) {
            picker.setSelectLimit(maxImgCount);
        }
        mSelImageList = new ArrayList<>();
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        mSignInfo = extras.getParcelable("SIGN_INFO_DTO");

    }

    @Override
    public void initData() {
        Intent intent = getIntent();
        mSignTypes = intent.getParcelableArrayListExtra("SIGN_TYPES");
        mSignId = intent.getIntExtra("SIGN_ID", -1);
        mType = intent.getIntExtra("TYPE", -1);
        mTypeRecyclerview.setLayoutManager(new GridLayoutManager(this, 4));
        mTypeRecyclerview.setHasFixedSize(true);
        mAdapter = new HxMatterRecycleAdapter(this, mSignTypes);

        mTypeRecyclerview.setAdapter(mAdapter);


        mImagePickerAdapter = new ImagePickerAdapter(this, mSelImageList, maxImgCount);
        mImagePickerAdapter.setOnItemClickListener(this);
        mImagePickerAdapter.setDeleteItemClickListener(this);
        mPickerRecyclerview.setLayoutManager(new GridLayoutManager(this, 4));
        mPickerRecyclerview.setHasFixedSize(true);
        mPickerRecyclerview.setAdapter(mImagePickerAdapter);

        mImagePickerAdapter.setEdit(false);
        fetchWorkMatters();
        fetchWorkDes();
        fetchWorkPicker();

        mAdapter.setItemOnClickListener(new HxMatterRecycleAdapter.OnItemClickListener() {
            @Override
            public void OnItemClickListener(List<String> matters) {
                Log.d(TAG, "onClickListener: ----->" + matters);
                ToastUtil.showToast(matters + "");
                mMatters = matters;
            }
        });
    }

    /**
     * @desc 获取图片
     * @author songxf
     * created at 2017/8/1 15:33
     */
    private void fetchWorkPicker() {
        try {
            List<SignInfoDTO.InImgUrlsBean> inImgUrls1 = mSignInfo.getInImgUrls();
            List<SignInfoDTO.BackImgUrlsBean> backImgUrls1 = mSignInfo.getBackImgUrls();
            if (mType == SignFragment.TYPE_SIGN_IN) { //签到标识
                for (SignInfoDTO.InImgUrlsBean inImgUrl : inImgUrls1) {
                    setEditUrlToAdapter(inImgUrl.getInImgUrl(), inImgUrl.getId());
                }
            } else if (mType == SignFragment.TYPE_SIGN_OUT) { //签退标识
                for (SignInfoDTO.BackImgUrlsBean backImgUrl : backImgUrls1) {
                    setEditUrlToAdapter(backImgUrl.getBackImgUrl(), backImgUrl.getId());
                }
            }
        } catch (NullPointerException e) {

        }
    }

    private void setEditUrlToAdapter(String url, int id) {
        ImageItem imageItem = new ImageItem();
        imageItem.path = url;
        imageItem.name = id + "";
        mSelImageList.add(imageItem);
        mImagePickerAdapter.setImages(mSelImageList);
    }

    /**
     * @desc 把Glide缓存Bitmap转成File  遗弃
     * @author songxf
     * created at 2017/8/1 15:29
     */
    private void glideCacheBitmapToFile(String url) {
        final ImageItem imageItem = new ImageItem();
        if (TextUtils.isEmpty(url)) {
            return;
        }
       /* Glide.with(this).load(url).asBitmap().into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                File file = HxFileUtil.bitmapToFile(resource, mImgCache, System.currentTimeMillis() + "");

            }
        });*/
    }


    /**
     * @desc 取出之前提交的工作事项选择
     * @author songxf
     * created at 2017/7/27 18:13
     */
    private void fetchWorkMatters() {
        List<SignInfoDTO.InTypeIdsBean> inTypeIds = mSignInfo.getInTypeIds();
        List<SignInfoDTO.BackTypeIdsBean> backTypeIds = mSignInfo.getBackTypeIds();
        for (SignInfoDTO.SignTypesBean signTypesBean : mSignTypes) {
            if (mType == SignFragment.TYPE_SIGN_IN) {  //签到标识
                for (SignInfoDTO.InTypeIdsBean inTypeId : inTypeIds) {
                    if (signTypesBean.getId() == Integer.parseInt(inTypeId.getId())) {
                        signTypesBean.setCheck(true);
                    }
                }
            } else if (mType == SignFragment.TYPE_SIGN_OUT) { //签退标识
                for (SignInfoDTO.BackTypeIdsBean backTypeId : backTypeIds) {
                    if (signTypesBean.getId() == Integer.parseInt(backTypeId.getId())) {
                        signTypesBean.setCheck(true);
                    }
                }
            }
        }
        for (SignInfoDTO.SignTypesBean signTypesBean : mSignTypes) {
            if (signTypesBean.isCheck()) {
                mMatters.add(signTypesBean.getId() + "");
            }
        }
    }

    /**
     * @desc 获取之前提交的工作描述
     * @author songxf
     * created at 2017/7/27 18:16
     */
    private void fetchWorkDes() {
        String des = null;
        if (mType == SignFragment.TYPE_SIGN_IN) {  //签到标识
            des = mSignInfo.getInDes();
        } else if (mType == SignFragment.TYPE_SIGN_OUT) { //签退标识
            des = mSignInfo.getBackDes();
        }
        mDesEt.setText((des + ""));
        //设置光标位置
        mDesEt.setSelection(des.length());
    }


    private boolean isEdit = false;

    @OnClick({R.id.more, R.id.toolbar, R.id.covere_ly})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.more:
                if (!isEdit) { //编辑
                    isEdit = !isEdit;
                    mMore.setText("提交");
                    mImagePickerAdapter.setEdit(true);
                    mCovereLy.setVisibility(View.GONE);
                } else { //提交
                    isEdit = !isEdit;
                    mMore.setText("编辑");
                    submitForm();
                }
                break;
            case R.id.toolbar:
                finish();
                break;
            case R.id.covere_ly:
                ToastUtil.showToast("编辑状态下才能修改");
                break;
        }
    }


    ArrayList<ImageItem> images = null;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    mSelImageList.addAll(images);
                    mImagePickerAdapter.setImages(mSelImageList);
                }
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    mSelImageList.clear();
                    mSelImageList.addAll(images);
                    mImagePickerAdapter.setImages(mSelImageList);
                }
            }
        }
    }


    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                //打开选择,本次允许选择的数量
                ImagePicker.getInstance().setSelectLimit(maxImgCount - mSelImageList.size());
                Intent intent1 = new Intent(getContext(), ImageGridActivity.class);
                                /* 如果需要进入选择的时候显示已经选中的图片，
                                 * 详情请查看ImagePickerActivity
                                 * */
                //                                intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES,images);
                startActivityForResult(intent1, REQUEST_CODE_SELECT);
                break;
            default:
                //打开预览
                Intent intentPreview = new Intent(getContext(), ImagePreviewDelActivity.class);

                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) mImagePickerAdapter.getImages());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                break;
        }
    }

    @Override
    public void onDeleteItemClick(int position) {
        if (mSelImageList.size() > 0) {
            ImageItem imageItem = mSelImageList.get(position);
            deleteItemImg(position, Integer.parseInt(imageItem.name));
        }
    }

    /**
     * @desc 删除图片
     * @author songxf
     * created at 2017/8/5 16:46
     */
    private void deleteItemImg(final int position, int imgId) {
        Call<BaseDTO> call = HxTransmitRequestHelper.getRequestApi().deleteSignImg(imgId);
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                if (response.isSuccessful() && response.body().getState() > 0) {
                    mSelImageList.remove(position);
                    mImagePickerAdapter.setImages(mSelImageList);
                }
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                ToastUtil.showToast("网络失败");
            }
        });
    }


    /**
     * @desc 提交表单
     * @author songxf
     * created at 2017/7/17 10:24
     * 接口 addSignInfo
     * signId 整形
     * file 文件
     * typeIds 字符串
     * des 字符串
     */
    public void submitForm() {
        String desEd = mDesEt.getText().toString();
        //图片路径集合
        List<String> imageDatas = new ArrayList<>();
        if (TextUtils.isEmpty(desEd) && mSelImageList.size() == 0 && mMatters == null) {
            ToastUtil.showToast("没有内容");
            return;
        }
        for (int i = 0; i < mSelImageList.size(); i++) {
            String path = mSelImageList.get(i).path;
            imageDatas.add(path);
        }
        final ProgressDialog dialog = DialogUtil.getWaitDialog(this, "提交中...");
        dialog.show();
        Log.d(TAG, "--描述内容-->" + desEd);
        Log.d(TAG, "--图片路径-->" + imageDatas);
        Log.d(TAG, "--mSignId-->" + mSignId);
        Log.d(TAG, "--mMatters-->" + listDecan(mMatters));
        //启动压缩
        Log.d(TAG, "--type-->" + mType);
        String[] imageS = imageDatas.toArray(new String[imageDatas.size()]);
        Call<BaseDTO> call = HxTransmitRequestHelper.getRequestApi().commitAddSignIfo(mSignId, RequestHelper.createFileParts(imageS)
                , listDecan(mMatters), desEd, mType);
        Log.d(TAG, "submitForm: --->" + call.request().url());
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                BaseDTO baseDTO = response.body();
                dialog.dismiss();
                if (response.isSuccessful()) {
                    if (baseDTO != null && baseDTO.getState() > 0) {
                        ToastUtil.showToast(getString(R.string.submit_success));
                        EventBus.getDefault().post(new HxIsRefreshEventBus(true));
                        finish();
                    } else {
                        ToastUtil.showToast(getString(R.string.submit_faile));
                    }
                } else {
                    ToastUtil.showToast(getString(R.string.submit_faile));
                }
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                dialog.dismiss();
                ToastUtil.showToast(getString(R.string.network_faile));
            }
        });
    }


    /**
     * @desc 去掉 list 中括号
     * @author songxf
     * created at 2017/7/26 17:54
     */
    private String listDecan(List<String> str) {
        if (str==null || str.size()==0){
            return null;
        }
        StringBuilder strBuilder = new StringBuilder();
        for (int i = 0; i < str.size(); i++) {
            strBuilder.append(str.get(i) + ",");
        }
        return strBuilder.substring(0, strBuilder.length() - 1);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        HxFileUtil.deleteFilesByDirectory(new File(mImgCache));
    }
}
